package net.itxxw.govern.gateway.filter;


import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import net.itxxw.framework.model.response.CommonCode;
import net.itxxw.framework.model.response.ResponseResult;
import net.itxxw.govern.gateway.service.AuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author：ycpan
 * @date：Created in 2021/5/30 22:04
 * @description：网关过滤器
 * @modified By：
 * @version: $*/



@Component
public class LoginFilter extends ZuulFilter {
    private static final Logger LOG = LoggerFactory.getLogger(LoginFilter.class);

/**
     * 设置过滤器的类型
     * 1.pre：请求在被路由之前执行
     * 2.routing：在路由请求时调用
     * 3.post：在routing和error过滤器之后调用
     * 4.error：处理请求时发生错误调用*/


    @Autowired
    AuthService authService;

    @Override
    public String filterType() {
        return "pre";
    }
    @Override
    public int filterOrder() {
        return 0;//int值来定义过滤器的执行顺序，数值越小优先级越高
    }
    @Override
    public boolean shouldFilter() {// 该过滤器需要执行
        return true;
    }
    @Override
    public Object run() {
        //上下文对象
        RequestContext requestContext = RequestContext.getCurrentContext();
       //请求对象
        HttpServletRequest request = requestContext.getRequest();
       //查询身份令牌
        String access_token = authService.getTokenFromCookie(request);
        if(access_token==null){
            //拒绝访问
            access_denied();
            return null;
        }
        //从redis中校验身份令牌是否过期
        long expire = authService.getExpire(access_token);
        if(expire<=0){
            access_denied();
            return null;
        }
        //查询jwt令牌
        String jwt = authService.getJwtFromHeader(request);
        if (jwt==null){
            access_denied();
            return null;
        }

        return null;
    }

    private void access_denied() {
        //上下文对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        //拒绝访问
        requestContext.setSendZuulResponse(false);
        //设置响应内容
        ResponseResult responseResult = new ResponseResult(CommonCode.UNAUTHENTICATED);
        String responseResultString = JSON.toJSONString(responseResult);
        requestContext.setResponseBody(responseResultString);
        //设置状态码
        requestContext.setResponseStatusCode(200);
        //获取响应内容
        HttpServletResponse response = requestContext.getResponse();
        response.setContentType("application/json;charset=utf-8");
    }
}
